how to update child records when updating the Master table using Linq [closed]

Posted by user20358 on Programmers See other posts from Programmers or by user20358
Published on 2012-05-31T12:10:59Z Indexed on 2012/05/31 16:50 UTC
Read the original article Hit count: 326

Filed under:
|

I currently use a general repositry class that can update only a single table like so

public abstract class MyRepository<T> : IRepository<T>
        where T : class
{


    protected IObjectSet<T> _objectSet;
    protected ObjectContext _context;

    public MyRepository(ObjectContext Context)
    {
        _objectSet = Context.CreateObjectSet<T>();
        _context = Context;
    }


    public IQueryable<T> GetAll()
    {
        return _objectSet.AsQueryable();
    }

    public IQueryable<T> Find(Expression<Func<T, bool>> filter)
    {
        return _objectSet.Where(filter);
    }

    public void Add(T entity)
    {
        _objectSet.AddObject(entity);
        _context.ObjectStateManager.ChangeObjectState(entity, System.Data.EntityState.Added);
        _context.SaveChanges();
    }

    public void Update(T entity)
    {
        _context.ObjectStateManager.ChangeObjectState(entity, System.Data.EntityState.Modified);
        _context.SaveChanges();
    }

    public void Delete(T entity)
    {
        _objectSet.Attach(entity);
        _context.ObjectStateManager.ChangeObjectState(entity, System.Data.EntityState.Deleted);
        _objectSet.DeleteObject(entity);
        _context.SaveChanges();
    }

}

For every table class generated by my EDMX designer I create another class like this

public class CustomerRepo : MyRepository<Customer>
{
    public CustomerRepo (ObjectContext context)
        : base(context)
    {

    }
}

for any updates that I need to make to a particular table I do this:

Customer CustomerObj = new Customer();
CustomerObj.Prop1 = ...
CustomerObj.Prop2 = ...
CustomerObj.Prop3 = ...
CustomerRepo.Update(CustomerObj);

This works perfectly well when I am updating just to the specific table called Customer. Now if I need to also update each row of another table which is a child of Customer called Orders what changes do I need to make to the class MyRepository. Orders table will have multiple records for a Customer record and multiple fields too, say for example Field1, Field2, Field3.

So my questions are:

1.) If I only need to update Field1 of the Orders table for some rows based on a condition and Field2 for some other rows based on a different condition then what changes I need to do?

2.) If there is no such condition and all child rows need to be updated with the same value for all rows then what changes do I need to do?

Thanks for taking the time. Look forward to your inputs...

© Programmers or respective owner

Related posts about entity-framework

Related posts about LINQ